﻿using System.Windows.Media;
using System.Xml.Linq;

namespace TicTacToe.Core.Persistance
{
    public static class Serialization
    {
        public static XElement Serialize(this Player player)
        {
            return new XElement("player",
                new XElement("name", player.Name),
                new XElement("color",
                    new XElement("a", player.Color.A),
                    new XElement("r", player.Color.R),
                    new XElement("g", player.Color.G),
                    new XElement("b", player.Color.B)),
                new XElement("id", player.ID));
        }

        public static XElement Serialize(this Turn turn)
        {
            return new XElement("turn",
                Serialize(turn.Player),
                new XElement("x1", turn.X1),
                new XElement("x2", turn.X2),
                new XElement("x3", turn.X3));
        }

        public static Player DeserializeToPlayer(this XElement obj)
        {
            var name = obj.Element("name").Value;
            var id = obj.Element("id").Value;
            var c = obj.Element("color");

            var a = c.Element("a").Value.ToByte();
            var r = c.Element("r").Value.ToByte();
            var g = c.Element("g").Value.ToByte();
            var b = c.Element("b").Value.ToByte();

            return new Player(name, new Color { A = a, R = r, G = g, B = b }, id);
        }

        public static Turn DeserializeToTurn(this XElement obj)
        {
            var player = DeserializeToPlayer(obj.Element("player"));
            var x1 = obj.Element("x1").Value.ToInt();
            var x2 = obj.Element("x2").Value.ToInt();
            var x3 = obj.Element("x3").Value.ToInt();

            return new Turn(player, x1, x2, x3);
        }
    }
}
